package com.arox.springinaction.post;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PostMain {
    public static String FRONTDESK_IMPL = "frontDeskTemplate";
    public static String BACKOFFICE_IMPL = "backOfficeTemplate";
    
    public static void main(String[] args) {
	final ApplicationContext appContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
	final FrontDesk frontDesk = (FrontDesk) appContext.getBean(FRONTDESK_IMPL);
	Thread frontDeskTh = new Thread(new Runnable() {
	    public void run() {
		for (int i = 0; i < 10; i++) {
		    Mail mail = new Mail("Mail No. " + i, "US", 1.5);
		    frontDesk.sendMail(mail);
		    System.out.println("Mail #" + mail.getMailId() + " sent!");
		    try {
			Thread.sleep(1000);
		    } catch (InterruptedException ex) {
			frontDesk.sendMail(new Mail("Error mail", "US", 1.5));
		    }
		}
	    }
	}, "frontDeskTh");
	final BackOffice backOffice = (BackOffice) appContext.getBean(BACKOFFICE_IMPL);
	Thread backOfficeTh = new Thread(new Runnable() {
	    public void run() {
		long startListening = System.currentTimeMillis();
		while (true) {
		    Mail mail = backOffice.receiveMail();
		    if (mail != null) {
			System.out.println("Mail #" + mail.getMailId() + " received!");
		    } else {
			try {
			    Thread.sleep(50);
			} catch (InterruptedException ex) {
			}
		    }
		    // Listen for 15 seconds
		    if (startListening + 15000 < System.currentTimeMillis()) {
			break;
		    }
		}
	    }
	}, "backOfficeTh");
	// start threads
	backOfficeTh.start();
	try {
	    Thread.sleep(50);
	} catch (InterruptedException ex) {
	}
	frontDeskTh.start();
    }
}
